﻿var currentNode = null;
//var oldConfirm = radconfirm;

function GetHeight() 
{
    var myHeight = 0;
    if( typeof( window.innerWidth ) == 'number' )
    {
        //Non-IE
        myHeight = window.innerHeight;
    }
    else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
    {
        //IE 6+ in 'standards compliant mode'
        myHeight = document.documentElement.clientHeight;
    }
    else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
    {
        //IE 4 compatible
        myHeight = document.body.clientHeight;
    }
    return myHeight;
}

function RowDblClick(sender, eventArgs) 
{
    sender.get_masterTableView().editItem(eventArgs.get_itemIndexHierarchical());
}

function onNodeMouseOver(sender, args) 
{
    currentNode = args.get_node();
}

function onNodeMouseOut(sender, args) 
{
    currentNode = null;
}

function ShowToolTip() {
    window.setTimeout(function() {
        var tooltip = $find("RadToolTip1");
        //API: show the tooltip
        tooltip.show();
    }, 10);
    
}
function CheckIfShow(sender, args) {
    var summaryElem = document.getElementById("ValidationSummary1");

    //check if summary is visible
    if (summaryElem.style.display == "none") {
        //API: if there are no errors, do not show the tooltip
        args.set_cancel(true);
    }
}

// ComboBox

function onSuccess(result) 
{
    //get instance of the RadComboBox client-side object
    var comboBox = $find("<%= RadComboBox1.ClientID %>");

    //remove all combobox items
    comboBox.get_items().clear();

    //the result in JSON format is available as a "d" field
    var customers = result.d;

    //Traverse the array of objects and create combobox items
    for (var i = 0; i < customers.length; i++) {
        var customer = customers[i];

        var comboBoxItem = new Telerik.Web.UI.RadComboBoxItem();
        comboBoxItem.set_text(customer.ContactName);
        comboBox.get_items().add(comboBoxItem);
    }

    //Highlight the matches based on the combobox text
    comboBox.highlightAllMatches(comboBox.get_text());
}

function itemsRequesting(sender, args) {
    var filter = "";

    //Set the filter if the user typed some text
    var text = args.get_text();
    
    if (text != "")
        filter = "&$filter=substringof('" + text + "', ContactName)";

    //Call the ADO.NET Data Service
    $telerik.$.ajax({
        type: "GET", // HTTP method
        url: '<%= ResolveUrl("ComboBoxAdoNetService.svc/Customers?$orderby=ContactName") %>' + filter, // ADO.NET DataService URL
        contentType: "application/json; charset=utf-8", //request the result to be in JSON
        dataType: "json",
        success: onSuccess //callback method to invoke when the request is complete
    });

    //Prevent the default load on demand
    args.set_cancel(true);
}


//window.radconfirm = function(text, mozEvent)  
//We will change the radconfirm function so it takes all the original radconfirm attributes
window.radconfirm = function(text, mozEvent, oWidth, oHeight, callerObj, oTitle) 
{
    var ev = mozEvent ? mozEvent : window.event; //Moz support requires passing the event argument manually     
    //Cancel the event     
    ev.cancelBubble = true;
    ev.returnValue = false;
    if (ev.stopPropagation) ev.stopPropagation();
    if (ev.preventDefault) ev.preventDefault();

    //Determine who is the caller     
    var callerObj = ev.srcElement ? ev.srcElement : ev.target;

    //Call the original radconfirm and pass it all necessary parameters
    if (callerObj) 
    {
        //Show the confirm, then when it is closing, if returned VALUES was true, automatically call the caller's click method again.     
        var callBackFn = function(arg) {
            if (arg) {
                callerObj["onclick"] = "";
                if (callerObj.click) callerObj.click(); //Works fine every time in IE, but does not work for links in Moz     
                else if (callerObj.tagName == "A") //We assume it is a link button!     
                {
                    try {
                        eval(callerObj.href)
                    }
                    catch (e) { }
                }
            }
        }
        //oldConfirm(text, callBackFn, 300, 100, null, null);         
        //We will need to modify the oldconfirm as well                  
        oldConfirm(text, callBackFn, oWidth, oHeight, callerObj, oTitle);
    }
    return false;
} 


var dtCh = "/";

function PopUpShowingCenter(sender, eventArgs) 
{
    var popUp;
    popUp = eventArgs.get_popUp();
    var gridWidth = sender.get_element().offsetWidth;
    var gridHeight = sender.get_element().offsetHeight;
    var popUpWidth = popUp.style.width.substr(0, popUp.style.width.indexOf("px"));
    var popUpHeight = popUp.style.height.substr(0, popUp.style.height.indexOf("px"));
    popUp.style.left = ((gridWidth - popUpWidth) / 2 + sender.get_element().offsetLeft).toString() + "px";
    popUp.style.top = ((gridHeight - popUpHeight) / 2 + sender.get_element().offsetTop).toString() + "px";
}

function openRadWin(formname, popname) 
{
    var oWnd = radopen(formname, popname);
}

function onRowDropping(sender, args) 
{
    if (currentNode) 
    {
        $get("nodeValueHiddenField").value = currentNode.get_value();
        args.set_destinationHtmlElement("nodeValueHiddenField");
    }
    else 
    {
        args.set_cancel(true);
    }
}

function daysInFebruary(year) {
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    year = year - 543;
    return (((year % 4 == 0) && ((!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28);
}
function DaysArray(n) {
    for (var i = 1; i <= n; i++) {
        this[i] = 31
        if (i == 4 || i == 6 || i == 9 || i == 11) { this[i] = 30 }
        if (i == 2) { this[i] = 29 }
    }
    return this
}

function validateDate(src, args) {
    if (args.Value.length > 0) {
        if (isDate(args.Value) == false) {
            args.IsValid = false;
        }
    }
}

function isDate(dtStr) {
    var daysInMonth = DaysArray(12)
    var pos1 = dtStr.indexOf(dtCh)
    var pos2 = dtStr.indexOf(dtCh, pos1 + 1)
    var strDay = dtStr.substring(0, pos1)
    var strMonth = dtStr.substring(pos1 + 1, pos2)
    var strYear = dtStr.substring(pos2 + 1)
    strYr = strYear
    if (strDay.charAt(1) == "0" && strDay.length > 1) strDay = strDay.substring(2)
    if (strMonth.charAt(0) == "0" && strMonth.length > 1) strMonth = strMonth.substring(1)
    for (var i = 1; i <= 3; i++) {
        if (strYr.charAt(0) == "0" && strYr.length > 1) strYr = strYr.substring(1)
    }
    month = parseInt(strMonth)
    day = parseInt(strDay)
    year = parseInt(strYr)
    if (pos1 == -1 || pos2 == -1) {
        return false
    }
    if (strMonth.length < 1 || month < 1 || month > 12) {
        return false
    }
    if (strDay.length < 1 || day < 1 || day > 31 || (month == 2 && day > daysInFebruary(year)) || day > daysInMonth[month]) {
        return false
    }
    if (strYear.length != 4 || year == 0) {
        return false
    }
    return true
}

function changeMonthNumberToName(month_number) {
    var months = new Array(12);
    months[1] = "มกราคม";
    months[2] = "กุมภาพันธ์";
    months[3] = "มีนาคม";
    months[4] = "เมษายน";
    months[5] = "พฤษภาคม";
    months[6] = "มิถุนายน";
    months[7] = "กรกฎาคม";
    months[8] = "สิงหาคม";
    months[9] = "กันยายน";
    months[10] = "ตุลาคม";
    months[11] = "พฤศจิกายน";
    months[12] = "ธันวาคม";
    return months[month_number];
}

function MultipleFieldsValidatorEvaluateIsValid(val) {
    controltovalidateIDs = val.controlstovalidate.split(',');
    switch (val.condition) {
        case 'OR':
            for(var controltovalidateIDIndex in controltovalidateIDs) {
                var controlID = controltovalidateIDs[controltovalidateIDIndex];
                if (ValidatorTrim(ValidatorGetValue(controlID)) != '') {
                    return true;
                } 
            }
            return false;
        break;
        case 'XOR':
            for(var controltovalidateIDIndex in controltovalidateIDs) {
                var controlID = controltovalidateIDs[controltovalidateIDIndex];
                if (controltovalidateIDIndex == '0') {
                    var previousResult = !(ValidatorTrim(ValidatorGetValue(controlID)) == '');
                    continue;
                }
                var currentResult = !(ValidatorTrim(ValidatorGetValue(controlID)) == '');
                if (currentResult != previousResult) {
                    return true;
                }
                previousResult != currentResult;
            }
            return false;
        break;
        case 'AND':
            for(var controltovalidateIDIndex in controltovalidateIDs) {
                var controlID = controltovalidateIDs[controltovalidateIDIndex];
                if (ValidatorTrim(ValidatorGetValue(controlID)) == '') {
                    return false;
                } 
            }
            return true;
        break;
    }
    return false;
}

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.search);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}